package com.mqtt.mqtt;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.mqtt.MqttApplication;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @Author xiaowen
 * @Email xiaowen.wxf@google.com
 * @Date 2018/10/19 .
 * @Description This is Mqtt.
 */
public class Mqtt {

    private MqttAndroidClient mqttAndroidClient;
    private static final String TAG = "QAQAQAAAAAAAA";
    private MqttConnectionBean mMqttConnectionBean;

    private Context mContext;

    public Mqtt(Context context, MqttConnectionBean mqttConnectionBean) throws Exception {
        this.mContext = context;
        this.mMqttConnectionBean = mqttConnectionBean;
        if (null == mqttConnectionBean) {
            throw new Exception("MqttConnectionBean 不能为空");
        }
        initMqtt();
    }

    private void initMqtt() {

        mqttAndroidClient = new MqttAndroidClient(mContext, mMqttConnectionBean.getBroker_ip(), mMqttConnectionBean.getClientId());
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
            }

            @Override
            public void connectionLost(Throwable cause) {
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName("TEST");
        mqttConnectOptions.setPassword("TEST".toCharArray());

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                    Toast.makeText(mContext, "连接成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }

    private void subscribeToTopic() {
        try {
            mqttAndroidClient.subscribe(mMqttConnectionBean.getTopic(), mMqttConnectionBean.getQos(), null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                }
            });

            // THIS DOES NOT WORK!
            mqttAndroidClient.subscribe(mMqttConnectionBean.getTopic(), mMqttConnectionBean.getQos(), new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 消息发送成功
                    Log.e(TAG, "===消息发送成功==== message = " + message);
                }
            });

        } catch (MqttException ex) {
            ex.printStackTrace();
            Log.e(TAG, "===subscribeToTopic====onFailure== ", ex);
        }
    }

    public void publishMessage(String msg) {
        try {
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setPayload(msg.getBytes());//设置消息内容
            mqttMessage.setRetained(mMqttConnectionBean.isRetained()); //服务器是否保存最后一条消息，若保存，client再次上线时，将再次受到上次发送的最后一条消息。
            mqttMessage.setQos(mMqttConnectionBean.getQos());//设置消息发送质量
            mqttAndroidClient.publish(mMqttConnectionBean.getTopic(), mqttMessage);//设置消息的topic，并发送。
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "===publishMessage====onFailure== ", e);

        }
    }

    /**
     * 断开服务器链接
     */
    public void disConnect() {
        if (null == mqttAndroidClient) {
            return;
        }
        try {
            mqttAndroidClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public boolean isConnect(){
        try {
            return mqttAndroidClient.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}